/*
** free.c for malloc in /home/morel_t//Rendu/systemUnix/malloc
**
** Made by thomas morel
** Login   <morel_t@epitech.net>
**
** Started on  Thu Feb  2 15:54:39 2012 thomas morel
** Last update Fri Feb  3 11:46:22 2012 florian jousseau
*/

#include <pthread.h>
#include "alloc.h"

extern void	*g_first_block;
extern pthread_mutex_t g_mutex;

void	free(void *ptr)
{
  t_alloc	block;

  pthread_mutex_lock(&g_mutex);
  if (inside_heap(ptr))
    {
      block = get_mdata(ptr);
      block->free = 1;
      /* printf("block : %p\nblock->next : %p\nblock->prev : %p\n", block, block->next, block->prev); */
      if (block->prev && block->prev->free)
	block = merge_block(block->prev);
      if (block->next)
	merge_block(block);
      else
      	{
	  if (block->prev)
	    block->prev->next = NULL;
	  else
	    g_first_block = NULL;
	  brk(block);
	}
    }
  pthread_mutex_unlock(&g_mutex);
}
